package com.dzf.controller;

import com.dzf.entity.*;

import com.dzf.service.UserService;

import com.dzf.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author DZF
 * 用户前台模块-》个人信息
 */
@RequestMapping("/api/fore")
@RestController
public class ForeController {
    @Autowired
    UserService userService;
    @Autowired
    SessionUtil sessionUtil;

    /**
     * 更新密码
     * @param password 更新的密码
     * @return 无data
     */
    @PostMapping("/user/updatePwd")
    public RespJson updatePwd(String password)
    {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //获取用户后将密码给用户
        MyUser user = (MyUser) sessionUtil.getUser();
        user.setPassword(encoder.encode(password));
        userService.updatePwd(user);
        return RespJson.pack(200,"修改密码成功",null);
    }

    /**
     * 用户更新头像
     * @param img 图片文件
     * @return 更新后的图片ID
     */
    @RequestMapping("/user/updateImg")
    public RespJson updateImg(@RequestParam(value = "img",required = false) MultipartFile img)
    {
        //得到当前登录用户
        MyUser user = (MyUser) sessionUtil.getUser();
        //业务结束后把uuid返回
        String uuid = userService.updateImg(user, img);
        return RespJson.pack(200,"更新用户头像成功",uuid.toString().replace("-",""));
    }

    /**
     * 更新用户信息
     * @param nickname 用户名
     * @param phone 手机号
     * @return 无data
     */
    @RequestMapping("/user/updateInfo")
    public RespJson updateInfo(String nickname,String phone)
    {
        MyUser user = (MyUser) sessionUtil.getUser();
        user.setNickname(nickname);
        user.setPhone(phone);


        userService.updateInfo(user);
        return RespJson.pack(200,"OK",null);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
